package com.janko.springbootbase.controller.lock;

import org.springframework.util.StringUtils;

/**
 * @ClassName lockSynchronized
 * @Description Synchronized锁的相关方法
 * @Author janko
 * @Date 2020/12/11 11:17
 */
public class lockSynchronized {

    public static void main(String[] args) {
//        shunXuSynchronized();//线程顺序执行
        luanXuSynchronized();
    }

    static void shunXuSynchronized(){
        System.out.println("带锁的时候、线程顺序执行\n使用关键字synchronized");
        SyncThread syncThread = new SyncThread();
        Thread thread1 = new Thread(syncThread, "SyncThread1");
        Thread thread2 = new Thread(syncThread, "SyncThread2");
        thread1.start();
        thread2.start();
    }

    static void luanXuSynchronized(){
        /**
         * 这个时候是不锁定线程的、它是乱序执行线程
         */
        System.out.println("使用关键字synchronized每次调用进行new SyncThread()、等于是锁了不同的对象");
        Thread thread1 = new Thread(new SyncThread(), "SyncThread1");
        Thread thread2 = new Thread(new SyncThread(), "SyncThread2");
        thread1.start();
        thread2.start();
    }

    static class SyncThread implements Runnable {
        private static int count;
        public SyncThread() {
            count = 0;
        }
        public  void run() {
            synchronized (this){
                for (int i = 0; i < 5; i++) {
                    try {
                        System.out.println("线程名:"+Thread.currentThread().getName() + ":" + (count++));
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        public int getCount() {
            return count;
        }
    }
}
